'use strict';

const chalk = require('chalk');
const exec = require('shelljs').exec;
const child = exec('git diff --cached --name-only', {
	cwd: process.cwd(),
	silent: true
});
if (child.code) {
	process.exit(1);
} else {
	const modifyFiles = child.stdout.toString().trim().split('\n').filter(file => /^src/.test(file));
	inExcludeFile(modifyFiles).then((disSubmitFiles) => {
		if (disSubmitFiles.length) {
			disSubmitFiles.forEach((file) => {
				console.log(`${chalk.red('您没有此文件提交权限')} ${chalk.green(file)}`);
				console.log(`${chalk.red('您可用此移除暂存区')} ${chalk.green(`git reset -- ${file}`)}\n`);
			});
			process.exit(1);
		} else {
			console.log(chalk.green('提交成功, 您本周已提交3455行代码，加油！'));
		}
	});
}

function inExcludeFile(files) {
	return new Promise((resolve) => {
		let userEmail = exec('git config --get user.email', {
			cwd: process.cwd(),
			silent: true
		});
		userEmail = userEmail.stdout.toString();
		console.log(chalk.green('正在校验你的权限 ' + userEmail));
		setTimeout(() => {
			// 请求服务拉取当前用户可操作的目录
			const allowPaths = ['page3'];
			let disSubmitFiles = files.slice(0);
			disSubmitFiles.forEach((file, i) => {
				allowPaths.some((allowPath) => {
					const reg = new RegExp(`^src/${allowPath}`, 'i');
					if(reg.test(file)){
						disSubmitFiles[i] = null;
						return true;
					}
					return false;
				});
			});
			disSubmitFiles = disSubmitFiles.filter((file) => !!file);
			resolve(disSubmitFiles);
		}, 300, userEmail);
	});
}
